﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dln.Common;
using Dln.Common.Helper;
using Dln.Model;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Web.Script.Serialization;
using Bright.Library.BO.Pub;
using Dln.Handler;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

public partial class lltest : System.Web.UI.Page
{

    protected string getSignDigest31 = "http://192.168.2.85:9999/gateway/common/getSignDigest";
    protected string synRecipeInfo33 = "http://192.168.2.85:9999/gateway/recipe/synRecipeInfo";
    protected string synSignDataSearch35 = "http://192.168.2.85:9999/gateway/recipe/synSignDataSearch";
    protected string synDoctor32 = "http://192.168.2.85:9999/gateway/doctor/synDoctor";
    protected string synDoctorSearch34 = "http://192.168.2.85:9999//gateway/doctor/synDoctorSearch";
    protected string verifyData36 = "http://192.168.2.85:9999/gateway/recipe/verifyData";

    protected void Page_Load(object sender, EventArgs e)
    {
       var uptModel = SqlHelper.Context.From<Duty>().Where(d => d.Id == 1).ToFirstDefault();
        var aa = "";
        var a = HttpUtility.UrlEncode(uptModel.Name); 
        #region 3.2--3.4

        //string data32 = "{" +
        //              "\"head\": {" +
        //              "\"clientId\": \"2018011614312929\"," +
        //              "\"clientSecret\": \"2018011614312980\"" +
        //              "}," +
        //              "\"body\": {" +
        //              "\"doctorId\": \"\"," +
        //              "\"doctorIdType\": \"\"," +
        //              "\"orgCode\": \"\"," +
        //              "\"orgName\": \"\"," +
        //              "\"uid\": \"321322199112270218\"," +
        //              "\"uidCardType\": \"SF\"," +
        //              "\"doctorName\": \"张凤娇\"," +
        //              "\"phone\": \"15995851784\"," +
        //              "\"email\": \"\"," +
        //              "\"title\": \"\"," +
        //              "\"department\": \"心胸外科\"," +
        //              "\"secDepartment\": \"二级科室\"," +
        //              "\"speciality\": \"医师专长\"," +
        //              "\"telqualification\": \"31123\"," +
        //              "\"technicaltitle\": \"123213\"," +
        //              "\"position\": \"132312\"," +
        //              "\"organizationcode\": \"13123\"," +
        //              "\"doctorIdPic\": \"\"," +
        //              "\"uPic\": \"\"," +
        //              "\"idCardPic\": \"\"," +
        //              "\"idCardBackPic\": \"\"," +
        //              "\"titlePic\": \"\"" +
        //              "}}";

        //var reuslt32 = SynDoctor(data32);
        //if (!string.IsNullOrEmpty(reuslt32))
        //{
        //    var jsonObj32 = (JObject)JsonConvert.DeserializeObject(reuslt32);
        //    var openid = jsonObj32["openId"] + "";
        //    var reuslt = GynDoctorSearch(openid);
        //    if (!string.IsNullOrEmpty(reuslt))
        //    {
        //        var datajson = (JObject)JsonConvert.DeserializeObject(reuslt);
        //        var a = datajson["stamp1"]+"";

        //    }
        //}

        #endregion

        #region 3.1、3.3、3.5
        //string data = "originData=" +
        //              "<PRESCRIPTION><CARDID>0000000001</CARDID><SERIALNUMBER>20180116082746010001</SERIALNUMBER><PATICATEID>00</PATICATEID><YBCARDID>0000000001</YBCARDID><INOUT_TAG>1</INOUT_TAG><PATINAME>黄红亮</PATINAME><PATISEX>男</PATISEX><PATIAGE>33</PATIAGE><AGETYPE>岁</AGETYPE><DIAGORGID>0101010214</DIAGORGID><LOCORGID></LOCORGID><DOCTID>01</DOCTID><DOCTNAME>张凤娇</DOCTNAME><DIAGS><DIAG><DIAGID>I10.X02</DIAGID><DIAGNAME>高血压</DIAGNAME></DIAG></DIAGS><ITEMS><ITEM><ORDID>20180116082938010008_01</ORDID><ITEMID>01000010000M</ITEMID><ITEMNAME>奥美拉唑胶囊</ITEMNAME><DOSAGE>20.00</DOSAGE><DOSAGEUNIT>mg</DOSAGEUNIT><USAGEID>PO</USAGEID><FREQID>bid</FREQID><PERQUANTITY>1.00</PERQUANTITY><QUANTITY>2.00</QUANTITY><UNITNAME>粒</UNITNAME><FACTOR>1.00</FACTOR><PRICE>1.00</PRICE><TAG>1</TAG></ITEM><ITEM><ORDID>20180116082938010008_01</ORDID><ITEMID>01000011001F</ITEMID><ITEMNAME>氢氯吡格雷片(赛诺菲)</ITEMNAME><DOSAGE>75.00</DOSAGE><DOSAGEUNIT>mg</DOSAGEUNIT><USAGEID>PO</USAGEID><FREQID>qd</FREQID><PERQUANTITY>1.00</PERQUANTITY><QUANTITY>2.00</QUANTITY><UNITNAME>粒</UNITNAME><FACTOR>1.00</FACTOR><PRICE>19.57</PRICE><TAG>1</TAG></ITEM></ITEMS></PRESCRIPTION>";
        //var dataResult31 = GetSignDigest(data);
        //if (!string.IsNullOrEmpty(dataResult31))
        //{
        //    var datajson = (JObject)JsonConvert.DeserializeObject(dataResult31);
        //    var hashTypea = datajson["hashType"] + "";
        //    var hashValue = datajson["hashValue"] + "";

        //    var urId = "20180116082938010008_01" + DateTime.Now.ToString("yyyyMMddHHmmssff");
        //    var json = "{"
        //               + "\"signType\": \"0\","
        //               + "\"msg\": {" +
        //               "\"head\": {" +
        //               "\"clientId\": \"2018011614312929\"," +
        //               "\"templateId\": \"hash\"," +
        //               "\"clientSecret\": \"2018011614312980\"," +
        //               "\"channelID\": \"\"" +
        //               "}," +
        //               "\"body\": {" +
        //               "\"urId\": \"" + urId + "\"," +
        //               "\"openId\": \"4d913988e84110eaq66e4w62ddyb58132dd\"," +
        //               "\"doctorName\": \"张凤娇\"," +
        //               "\"patientName\": \"黄红亮\"," +
        //               "\"patientAge\": \"33\"," +
        //               "\"patientSex\": \"男\"," +
        //               "\"patientCard\": \"\"," +
        //               "\"patientCardType\": \"QT\"," +
        //               "\"recipeTime\": \"2017-06-11 11:32:33\"," +
        //               "\"subject\": \"奥美拉唑胶囊\"," +
        //               "\"hashValue\": \"" + hashValue + "\"," +
        //               "\"hashType\":\"" + hashTypea + "\"}}}";
        //    var dataResult33 = SynRecipeInfo(json);
        //    if (!string.IsNullOrEmpty(dataResult33))
        //    {
        //        var signDigestjson = (JObject)JsonConvert.DeserializeObject(dataResult33);
        //        var timeStampSignData = signDigestjson["timeStampSignData"] + "";//保存
        //        var uniqueId = signDigestjson["uniqueId"] + "";   //保存

        //        var dataResult35 = SynSignDataSearch(uniqueId);
        //        if (!string.IsNullOrEmpty(dataResult35))
        //        {
        //            var dataResult35json = (JObject)JsonConvert.DeserializeObject(dataResult35);
        //            var signedData = signDigestjson["signedData"] + "";//保存
        //            var stamp = signDigestjson["stamp"] + "";
        //        }
        //    }
        //}
        #endregion


        //var reuslt31 = RequestHelper.SendPost(getSignDigest31, data);

        //var jsonObj = (JObject)JsonConvert.DeserializeObject(reuslt31);
        //if (jsonObj != null && jsonObj["status"].ToString() == "0")
        //{
        //    var datajson = (JObject)JsonConvert.DeserializeObject(jsonObj["data"].ToString());
        //    if (datajson != null)
        //    {
        //        var hashTypea = datajson["hashType"];
        //        var hashValue = datajson["hashValue"];
        //        var urId = "20180116082938010008_01" + DateTime.Now.ToString("yyyyMMddHHmmssff");

        //        var json = "{"
        //                   + "\"signType\": \"3\","
        //                   + "\"msg\": {" +
        //                   "\"head\": {" +
        //                   "\"clientId\": \"2018011614312929\"," +
        //                   "\"templateId\": \"hash\"," +
        //                   "\"clientSecret\": \"2018011614312980\"," +
        //                   "\"channelID\": \"\"" +
        //                   "}," +
        //                   "\"body\": {" +
        //                   "\"urId\": \"" + urId + "\"," +
        //                   "\"openId\": \"4d913988e84110eaq66e4w62ddyb58132dd\"," +
        //                   "\"doctorName\": \"张凤娇\"," +
        //                   "\"patientName\": \"黄红亮\"," +
        //                   "\"patientAge\": \"33\"," +
        //                   "\"patientSex\": \"男\"," +
        //                   "\"patientCard\": \"\"," +
        //                   "\"patientCardType\": \"QT\"," +
        //                   "\"recipeTime\": \"2017-06-11 11:32:33\"," +
        //                   "\"subject\": \"奥美拉唑胶囊\"," +
        //                   "\"hashValue\": \"" + hashValue + "\"," +
        //                   "\"hashType\":\"" + hashTypea + "\"}}}";

        //    }
        //}
        //var reuslt1 = RequestHelper.SendRestPost(synRecipeInfo33, json);

        //        var json2 = "{" +
        //                    "\"head\": {" +
        //                    "\"clientId\": \"2018011614312929\"" +
        //                    "}," +
        //                    "\"body\": {" +
        //                    "\"uniqueId\": \"eb8428b1c0764cb0b24df77f0fbda6ec\"" +
        //                    "}}";


        //        //var reuslt2 = RequestHelper.SendRestPost(synSignDataSearch35, json2);

        //        var s =
        //            "MIIE4AYJKoZIhvcNAQcCoIIE0TCCBM0CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHAaCCA7UwggOxMIICmaADAgECAgkgEDVa8xCbSVQwDQYJKoZIhvcNAQEFBQAwQjELMAkGA1UEBhMCQ04xDTALBgNVBAoMBEJKQ0ExDzANBgNVBAsMBlBFUlNPTjETMBEGA1UEAwwKTVNTUENBIFJTQTAeFw0xODAxMTkwMDMyMTVaFw0yMzAxMTkwMTMyMTVaMIGOMQswCQYDVQQGDAJDTjEZMBcGA1UECgwQMjAwMDExMTExMTExMDAwMjESMBAGA1UEAwwJ5byg5Yek5aiHMVAwTgYKCZImiZPyLGQBAQxANGIwMmQ1OGJmNTVlYTI3ODAxYTQ2ZTJjYTNhMzQwYmMwNzRhMWI0OTVjNDg0ZTRjODFjOTM3YTI0ODRlODQzZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhhmVNZnJwiY6mOe6FlD6bgRr78UeutSzpoO5LrYeKU2LccTDdpyp7Hb2zMZjQDSRAuvpYOFFdnVxAgupToWpa0OGpZY6dWC1UivnkBjBc+jVpwGAfFIWaIOZKkXtZIqXqYUovjSojc2zD2zw5pvxAnWadcZHbATFDUEI0fOeWu8CAwEAAaOB4DCB3TAfBgNVHSMEGDAWgBQ3SdvmsH4OcYrF23meY5b4vFxWkzAdBgNVHQ4EFgQUXBcgRDs9da8tV+tNnnUfArq1wbIwCwYDVR0PBAQDAgbAMEwGCGCGSAGG+EQCBEA0ZDkxMzk4OGU4NDExMGVhcTY2ZTR3NjJkZHliNTgxMzJkZCYmSE83WFhVTVE2cXUrQ0dQeUNXWGtYYVdQT0pRMEAGA1UdIAQ5MDcwNQYJKoEchu8yAgIDMCgwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuYmpjYS5vcmcuY24vY3BzMA0GCSqGSIb3DQEBBQUAA4IBAQBSGu9Q5S7tR/IzTPrkqF6J+FLjY2+kXJ8NEuZsy6NqOVsX+SMmQt+Q9I14KwVHTt/T4wSoYuQ3ABaaPy52G1UljYS26TAh6PQY3BDis5fZgwtdk8InDXU5xUCjQz0cjfIBwTAp/8trqyVEOAM0Yz6GUGQ0o0dRQlRysKZLQt0HHajf+xJHMwMSLdsozSKxDi6H6wPiJx4aLIDxKBO5heV0mrD0uOHIkHtpjhzXkNvifQNA9yj1yx/ClpygSA6zRjFRYNwrvm3pYBVmTD0lx8xluMX+L/v1OqGx9Xf4/Vd0QlQQXLEIuqZxdONUY6Ms9JtbKoSdx8KGrrnI1kCw6MdSMYH0MIHxAgEBME8wQjELMAkGA1UEBhMCQ04xDTALBgNVBAoMBEJKQ0ExDzANBgNVBAsMBlBFUlNPTjETMBEGA1UEAwwKTVNTUENBIFJTQQIJIBA1WvMQm0lUMAkGBSsOAwIaBQAwDQYJKoZIhvcNAQEBBQAEgYBekgB3AL51pdEuPeNSzwJtQt69of4H+GCKuUSC0gfCJf/w1odHSKk6QalfQNu3Dcar6gC28+mvcdtSNWy+zrxucKfwhF5ssOjoC0ZSTbhrckzf4pe2JtI/iK271bYFZ+iJ2LIsb5ELe+mpJ1/VpywEFmCRRJHzJ/gcGiSAd2P/7w==";

        //        //var json1 = "{"+
        //        //            "\"head\": {" +
        //        //            "\"clientId\": \"2018011614312929\"," +
        //        //            "\"templateId\": \"hash\"," +
        //        //            "\"clientSecret\": \"2018011614312980\"," +
        //        //            "\"signResult\": \""+ s + "\"" +
        //        //            "}," +
        //        //            "\"body\": {" +
        //        //            "\"urId\": \"20180116082938010008_012018011911271491\"," +
        //        //            "\"openId\": \"4d913988e84110eaq66e4w62ddyb58132dd\"," +
        //        //            "\"doctorName\": \"张凤娇\"," +
        //        //            "\"patientName\": \"黄红亮\"," +
        //        //            "\"patientAge\": \"33\"," +
        //        //            "\"patientSex\": \"男\"," +
        //        //            "\"patientCard\": \"\"," +
        //        //            "\"patientCardType\": \"QT\"," +
        //        //            "\"recipeTime\": \"2017-06-11 11:32:33\"," +
        //        //            "\"subject\": \"奥美拉唑胶囊\"," +
        //        //            "\"hashValue\": \"" + hashValue + "\"," +
        //        //            "\"hashType\":\"" + hashTypea + "\"}}";

        //var reuslt21 = RequestHelper.SendRestPost(verifyData36, json1);
        //    }

        //}

    }

    public string GetAuthOpenId()
    {
        string AppId = CommonHelper.GetAppSettings("AppID");
        string AppSecret = CommonHelper.GetAppSettings("AppSecret");
        string strOpenId = "";
        string name = "";
        string code = DNTRequest.GetString("CODE");

        var cookies = HttpContext.Current.Request.Cookies["openidcookie"];
        if (cookies != null && !string.IsNullOrEmpty(cookies.Value))
        {
            strOpenId = cookies.Value;
        }
        else
        {
            if (!String.IsNullOrEmpty(code))
            {
                string json =
                    RequestHelper.SendGet(
                        String.Format(
                            "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                            AppId, AppSecret, code));
                if (!String.IsNullOrEmpty(json))
                {
                    try
                    {
                        OAuthConfig oAuthConfig = JSONHelper.FromJson<OAuthConfig>(json);
                        if (oAuthConfig != null)
                        {
                            HttpCookie cookie = new HttpCookie("openidcookie");
                            cookie.Value = oAuthConfig.openid;
                            cookie.Expires = DateTime.Now.AddDays(2);
                            HttpContext.Current.Response.Cookies.Add(cookie);
                            strOpenId = oAuthConfig.openid;
                        }

                        else
                        {
                            strOpenId = "";
                        }
                    }
                    catch (Exception ex)
                    {
                        strOpenId = "";
                    }
                }
            }
            else
            {
                var url =
                    string.Format(
                        "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}%2Flltest.aspx&response_type=code&scope=snsapi_base&state=test#wechat_redirect",
                        AppId, CommonHelper.GetAppSettings("mainurl").Replace(@"://", "%3A%2F%2F"));
                Response.Redirect(url);

            }
        }
        return strOpenId;
    }

    public void ResponseToPage(string message)
    {
        Response.Redirect(String.Format("/page/Common/message.aspx?m={0}", Server.UrlEncode(message)));
    }


    /// <summary>
    /// 同步医师信息服务3.2
    /// </summary>
    /// <param name="data32"></param>
    /// <returns></returns>
    public string SynDoctor(string data32)
    {
        var reuslt32 = RequestHelper.SendRestPost(synDoctor32, data32);
        var jsonObj32 = (JObject)JsonConvert.DeserializeObject(reuslt32);
        if (jsonObj32 != null && jsonObj32["status"].ToString() == "0" && jsonObj32["data"] != null)
        {
            return jsonObj32["data"].ToString();
        }
        return "";
    }

    /// <summary>
    /// 同步医师信息服务3.1
    /// </summary>
    /// <param name="openid"></param>
    /// <returns></returns>
    public string GynDoctorSearch(string openid)
    {
        string data34 = "{" +
                        "\"head\": {" +
                        "\"clientId\": \"2018011614312929\"" +
                        "}," +
                        "\"body\": {" +
                        "\"openId\": \"" + openid + "\"" +
                        "}}";
        var reuslt = RequestHelper.SendRestPost(synDoctorSearch34, data34);
        var jsonObj34 = (JObject)JsonConvert.DeserializeObject(reuslt);
        if (jsonObj34 != null && jsonObj34["status"].ToString() == "0" && jsonObj34["data"] != null)
        {
            return jsonObj34["data"].ToString();
        }
        ////保存医生签章 stamp
        return "";
    }

    /// <summary>
    /// 3.1 签名指纹计算接口
    /// </summary>
    /// <param name="data31"></param>
    /// <returns></returns>
    public string GetSignDigest(string data31)
    {
        try
        {

            var reuslt31 = RequestHelper.SendPost(getSignDigest31, data31);
            var jsonObj = (JObject)JsonConvert.DeserializeObject(reuslt31);
            if (jsonObj != null && jsonObj["status"].ToString() == "0")
            {
                var datajson = (JObject)JsonConvert.DeserializeObject(jsonObj["data"] + "");
                if (datajson != null)
                {
                    return datajson + "";
                }
            }
        }
        catch
        {
            return "";
        }
        return "";
    }

    /// <summary>
    /// 3.3 签名数据同步接口
    /// </summary>
    /// <param name="data33"></param>
    /// <returns></returns>
    public string SynRecipeInfo(string data33)
    {
        try
        {
            var reuslt33 = RequestHelper.SendRestPost(synRecipeInfo33, data33);
            var jsonObj = (JObject)JsonConvert.DeserializeObject(reuslt33);
            if (jsonObj != null && jsonObj["status"].ToString() == "0" && jsonObj["data"] != null)
            {
                return jsonObj["data"] + "";
            }
        }
        catch
        {
            return "";
        }
        return "";
    }

    /// <summary>
    /// 3.5 签名数据签名结果查询
    /// </summary>
    /// <returns></returns>
    public string SynSignDataSearch(string data35)
    {
        try
        {
            var json = "{" +
                            "\"head\": {" +
                            "\"clientId\": \"2018011614312929\"" +
                            "}," +
                            "\"body\": {" +
                            "\"uniqueId\": \"" + data35 + "\"" +
                            "}}";


            var reuslt = RequestHelper.SendRestPost(synSignDataSearch35, json);
            var jsonObj35 = (JObject)JsonConvert.DeserializeObject(reuslt);
            if (jsonObj35 != null && jsonObj35["status"].ToString() == "0" && jsonObj35["data"] != null)
            {
                return jsonObj35["data"] + "";
            }
        }
        catch
        {
            return "";
        }
        return "";
    }
}
